//
//  ImageEditContainer.swift
//  TemplateImageEditDemo
//
//  Created by liguandong on 2024/4/11.
//

import Foundation
import UIKit
import SnapKit
/**
 所有模板图编辑区，添加模板，手势控制。
 */
class TemplateEditContainer4: UIView {
    private var editTemplateSingleContainer : TemplateSingleContainer4? = nil
//    private var templateImageViewList = [TemplateImageView4]()
    private var templateSingleContainerList = [TemplateSingleContainer4]()
    
    var onAddImage:((Int)->Void)?

    private lazy var bgImageView: UIImageView = {
        let v = UIImageView()
        v.image = templateInfo.bgImage
        v.contentMode = .scaleAspectFill
        return v
    }()
    
    
    private lazy var templateBackImageView: UIImageView = {
        let v = UIImageView()
        v.image = templateInfo.templateBackImage
        v.contentMode = .scaleAspectFill
        return v
    }()
    
    private lazy var subViewParent: UIView = {
        let v = UIView()
        return v
    }()
    
    private lazy var templateFontImageView: UIImageView = {
        let v = UIImageView()
        v.image = templateInfo.templateFontImage
        v.contentMode = .scaleAspectFill
        return v
    }()
    
    
    
    lazy var editView: TemplateEditView4 = {
        let v = TemplateEditView4()
        v.isUserInteractionEnabled = true
        v.isHidden = true
        v.onTransformUpate = {[weak self] in
            self?.editTemplateSingleContainer?.templateImageView.transform = v.transform
        }
        v.onRemoveViewBlock = {[weak self] in
            if let self = self {
                self.editView.isHidden = true
                self.editTemplateSingleContainer?.resetStatus()
                self.editTemplateSingleContainer = nil

            }
        }
        return v
    }()
    
    private lazy var panGesture: UIPanGestureRecognizer = {
        let panGesture = UIPanGestureRecognizer(target: self, action: #selector(panGestureAction(_:)))
        return panGesture
    }()
    
    private lazy var pinchGesture: UIPinchGestureRecognizer = {
        let pinchGesture = UIPinchGestureRecognizer(target: self, action: #selector(pinchAction(_:)))
        pinchGesture.delegate = self
        return pinchGesture
    }()

    private lazy var rotateGesture: UIRotationGestureRecognizer = {
        let rotateGesture = UIRotationGestureRecognizer(target: self, action: #selector(rotateAction(_:)))
        rotateGesture.delegate = self
        return rotateGesture
    }()
    
    private let templateInfo : TemplateInfo
    init(_ templateInfo : TemplateInfo){
        self.templateInfo = templateInfo
        super.init(frame: .zero)
        
        addSubview(bgImageView)
        addSubview(templateBackImageView)
        addSubview(subViewParent)
        addSubview(templateFontImageView)
        addSubview(editView)
        
        bgImageView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        templateBackImageView.snp.makeConstraints { make in
            make.width.equalToSuperview()
            make.height.equalTo(templateBackImageView.snp.width).multipliedBy(1.0 / TEMPLATE_RATIO)
            make.center.equalToSuperview()
        }
        subViewParent.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        templateFontImageView.snp.makeConstraints { make in
            make.width.equalToSuperview()
            make.height.equalTo(templateFontImageView.snp.width).multipliedBy(1.0 / TEMPLATE_RATIO)
            make.center.equalToSuperview()
        }
        editView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        addGestureRecognizer(panGesture)
        addGestureRecognizer(pinchGesture)
        addGestureRecognizer(rotateGesture)
        
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(onEmptyViewTap(_:)))
        addGestureRecognizer(tapGesture)

    }
    
    private var lastSize = CGSize.zero
    override func layoutSubviews() {
        super.layoutSubviews()
        if frame.size != lastSize {
            let viewRatio = frame.size.width / frame.size.height
            //模板图和view的高度差，需要位移居中
            let offsetImageY = (TEMPLATE_RATIO - viewRatio) * TEMPLATE_WIDTH / 2
            let scale = frame.size.width / TEMPLATE_WIDTH
            if subViewParent.subviews.count == 0 {
                for (i,imageFrame) in templateInfo.imageFrames.enumerated() {
                    let viewFrame = CGRect(x: imageFrame.origin.x * scale, y: imageFrame.origin.y * scale + offsetImageY, width: imageFrame.width * scale, height: imageFrame.height * scale)
                    
                    let subView = TemplateSingleContainer4(i)
                    subView.frame = viewFrame
                    let tapGesture = UITapGestureRecognizer(target: self, action: #selector(onImageTap(_:)))
                    subView.addGestureRecognizer(tapGesture)
                    templateSingleContainerList.append(subView)
                    subViewParent.addSubview(subView)
                }
            }else{
                for (i,subView) in subViewParent.subviews.enumerated() {
                    let imageFrame = templateInfo.imageFrames[i]
                    let viewFrame = CGRect(x: imageFrame.origin.x * scale, y: imageFrame.origin.y * scale + offsetImageY, width: imageFrame.width * scale, height: imageFrame.height * scale)
                    subView.frame = viewFrame
                    
                }
            }
            lastSize = frame.size
        }
    }

    private func setEditingTemplateImage(_ imageView : TemplateSingleContainer4){
        self.editView.isHidden = false
        self.editTemplateSingleContainer = imageView
        editView.resetState(imageView.templateImageView)
    }
    
    @available(*, unavailable)
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setImage(index:Int,image:UIImage){
        templateSingleContainerList[index].setImage(image)
    }
    
    // MARK: - Gesture Recognizer Actions
    @objc private func onEmptyViewTap(_ tapGesture: UITapGestureRecognizer) {
        debugPrint("onEmptyViewTap")
        self.editTemplateSingleContainer = nil
        self.editView.isHidden = true
    }
    
    @objc private func onImageTap(_ tapGesture: UITapGestureRecognizer) {
        debugPrint("onImageTap")
        if tapGesture.view is TemplateSingleContainer4 {
            let view = tapGesture.view as! TemplateSingleContainer4
            if view.image == nil {
                onAddImage?(view.index)
            }else{
                setEditingTemplateImage(view)
            }
        }
    }
    
    @objc func rotateAction(_ rotateGesture: UIRotationGestureRecognizer) {
        guard rotateGesture.numberOfTouches > 1 else {
            return
        }
        editView.rorateView(rotateGesture.rotation)
        rotateGesture.rotation = 0
    }
    
    @objc private func panGestureAction(_ panGesture: UIPanGestureRecognizer) {
        guard panGesture.state == .changed else { return }
        guard panGesture.numberOfTouches <= 1 else {
            panGesture.setTranslation(.zero, in: superview)
            return
        }
        let translation = panGesture.translation(in: superview)
        editView.translationView(x: translation.x, y: translation.y)
        panGesture.setTranslation(.zero, in: superview)
    }
    
    @objc private func pinchAction(_ pinchGesture: UIPinchGestureRecognizer) {
        guard pinchGesture.numberOfTouches > 1 else { return }
        let scale = pinchGesture.scale
        if editView.scaleView(scale){
            editView.onTransformUpate?()
        }
        pinchGesture.scale = 1
    }
}

// MARK: - UIGestureRecognizerDelegate

extension TemplateEditContainer4: UIGestureRecognizerDelegate {
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return true
    }
}
